<template>
	<view class="wrap">
		<u-skeleton rows="5" :loading="state.loading" :animate="true" v-if="state.loading"/>
		<form-run
			v-else
			:apply="true"
			:taskKey="state.form.firstTaskId"
			:form="state.form"
			:comps="state.comps"	
			:loading="state.submiting"
			@submit="onSubmit"
			@close="onClose"
		/>
	</view>
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app"
import { reactive } from 'vue'
import { request } from '../../utils/request'

const state = reactive({ params: {} as any, form: {} as any, comps: {} as any, id: '', loading: false, submiting: false })

const getStructure = (formId: string) => {
	state.loading = true
	request.get(`/flw/form-def-structure/form/${formId}`).then((resp: any) => {
		if (resp.success) {
			if (resp.data && resp.data.formJson) {
				const json = JSON.parse(resp.data.formJson)
				state.form = json.form
				state.comps = json.comps
				state.loading = false
			}
		}
	})	
}
	
onLoad((option) => {
	state.id = option.id
	getStructure(option.id)
})

const onSubmit = ({ title, formJson, formValue }: any) => {
	  const data = {
	    formJson,
	    formValue,
	    formInstanceName: title,
	    formId: state.id
	  }		
		state.submiting = true
		request.post('/flw/form-instance/start', { formInstance: data }).then((resp: any) => {
			state.submiting = false
	    if (resp.success) {
				uni.showToast({
					title: '表单已提交'
				})
	    }
		})
}
const onClose = () => {
	uni.navigateBack()
}

</script>

<style lang="scss" scoped>
</style>
